package com.wenkang.stu.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wenkang.stu.enums.ExceptionEnums;
import com.wenkang.stu.exception.KangException;
import com.wenkang.stu.pojo.SysMenu;
import com.wenkang.stu.pojo.SysRoleMenu;
import com.wenkang.stu.service.SysMenuService;
import com.wenkang.stu.service.SysRoleMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@RequestMapping("menu")
@RestController
public class MenuController {

    @Autowired
    private SysMenuService menuService;

    @Autowired
    private SysRoleMenuService roleMenuService;

    @GetMapping()
    public ResponseEntity<List<SysMenu>> getMenus() {
        List<SysMenu> menus = menuService.selectAllMenus();
        return ResponseEntity.ok(menus);
    }

    @GetMapping("user/{id}")
    public ResponseEntity<List<SysMenu>> getMenusByUserId(@PathVariable("id") String userId) {
        List<SysMenu> menus = menuService.selectMenusByUserId(userId);
        return ResponseEntity.ok(menus);
    }

    @GetMapping("role/{id}")
    public ResponseEntity<List<Integer>> getMenusByRoleId(@PathVariable("id") String roleId) {
        QueryWrapper<SysRoleMenu> queryWrapper = new QueryWrapper<>();
        queryWrapper = queryWrapper.eq("role_id", roleId);
        List<SysRoleMenu> menus = roleMenuService.list(queryWrapper);
        List<Integer> menusId = menus.stream().map(SysRoleMenu::getMenuId).collect(Collectors.toList());
        return ResponseEntity.ok(menusId);
    }

    @PostMapping()
    public ResponseEntity<Void> addMenu(@RequestBody SysMenu menu) {
        boolean success = menuService.save(menu);
        if (success) {
            return ResponseEntity.status(HttpStatus.CREATED).build();
        }
        throw new KangException(ExceptionEnums.CREATED_ERROR);
    }
}
